from django.shortcuts import render, redirect, HttpResponse
from django import forms

from accounts.utils.encrypt import md5
from accounts import models

from accounts.utils.bootstrap import BootStrapForm
from io import BytesIO
from accounts.utils.code import check_code


def image_code(request):
    """生成图片验证码"""
    img, code_str = check_code()

    request.session['image_code'] = code_str
    # 给session设置60秒超时
    request.session.set_expiry(60)

    stream = BytesIO()
    img.save(stream, "png")

    return HttpResponse(stream.getvalue())


class LoginForm(BootStrapForm):
    username = forms.CharField(
        label='用户名',
        widget=forms.TextInput,
        required=True
    )
    password = forms.CharField(
        label='密码',
        widget=forms.PasswordInput(render_value=True),  # 输入后密码不消失
        required=True
    )
    code = forms.CharField(
        label='验证码',
        widget=forms.TextInput,
        required=True
    )

    def clean_password(self):
        pwd = self.cleaned_data.get("password")
        return md5(pwd)


def login(request):
    if request.method == "GET":
        form = LoginForm()
        return render(request, 'auth/login.html', {'form': form})
    form = LoginForm(data=request.POST)
    if form.is_valid():

        # 为什么用pop 因为后续需要使用username和password到数据库进行校验，不能含有code
        user_input_code = form.cleaned_data.pop('code')
        code = request.session.get('image_code', '')
        if user_input_code.upper() != code.upper():
            form.add_error('code', '验证码错误')
            return render(request, 'auth/login.html', {'form': form})

        # admin_obj = models.Admin.objects.filter(username="xxx",password=pwd).first()
        # **form.cleaned_data 中字典中的字段名和LoginForm中设置的字段名一致，所以应保持LoginForm中字段名和数据库中一致
        admin_obj = models.Admin.objects.filter(**form.cleaned_data).first()
        if not admin_obj:
            # password表示 错误显示到password下面
            form.add_error('password', '用户名或密码错误')
            return render(request, 'auth/login.html', {'form': form})

        # 用户名密码正确
        # 网站随机生成字符串；写到用户浏览器的cookie中；再写到session中
        request.session['info'] = {'id': admin_obj.id, 'username': admin_obj.username}
        # 重新设置超时时间 7天
        request.session.set_expiry(60 * 60 * 24 * 7)
        return redirect('/admin/list/')

    return render(request, 'auth/login.html', {'form': form})


def logout(request):
    request.session.clear()
    return redirect('/login/')
